﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using LINQToolKit;

namespace  LINQToolKit.Douban.Entities
{
    public class EntityBase
    {
        public string Title { get; set; }
        public string Source { get; set; }
        public IList<Attribute> Attributes { get; set; }
        public IList<Link> Links { get; set; }
        public IList<Tag> Tags { get; set; }
        public AtomCategory AtomCategory { get; set; }
        public DateTime Published { get; set; }
        public DateTime Updated { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }

        public EntityBase()
        {
            this.Tags = new List<Tag>();
            this.Links = new List<Link>();
            this.Attributes = new List<Attribute>();
        }

        private string _id;

        public string ID 
        {
            get
            {
                if (string.IsNullOrEmpty(this._id) && !string.IsNullOrEmpty(this.Source))
                {
                    int index = this.Source.LastIndexOf('/');

                    if (index > 0) 
                    {
                        this._id = this.Source.Substring(index + 1);
                    }
                }

                return this._id;
            }
            set { this._id = value; }
        }

        public bool HasTag(string tagName)
        {
            tagName.AssertNull("tagName");

            foreach (var item in this.Tags)
            {
                if (item.Name == tagName)
                {
                    return true;
                }
            }

            return false;
        }

        public string GetLink(string name)
        {
            name.AssertNull("name");

            foreach (var item in this.Links)
            {
                if (item.Ref == name)
                {
                    return item.Href;
                }
            }

            return string.Empty;
        }

        public void SetAttribute(string name, string value)
        { 
            this.Attributes.Add(new Attribute{Name=name, Value = value});
        }

        public string GetAttribute(string name)
        {
            name.AssertNull("name");

            foreach (var item in this.Attributes)
            {
                if (item.Name == name)
                {
                    return item.Value;
                }
            }

            return string.Empty;
        }

        public IList<string> GetAttributes(string name)
        {
            var list = new List<string>();

            foreach (var item in this.Attributes)
            {
                if (item.Name == name)
                {
                    list.Add(item.Value);
                }
            }

            return list;
        }
    }
}
